<template>
  <view class="container1">
    <view :style="{height:(safeHeight*2)+'rpx'}"></view>
    <view class="mp-search-box">
      <view class="city">
        <image class="location-icon" src="/static/icon/address_icon.png" mode="aspectFit"></image>
        <text class="city-name">{{ currentCity || '南宁市' }}</text>
        <image class="down-icon" src="/static/icon/coupons_arrow.png" mode="aspectFit"></image>
      </view>
    </view>
    <view class="index-search-box index-search-box_re d-b-c" id="searchBox" @click="handleSearch()">
      <view class="index-search index-search_re t-c seacth">
        <span class="icon iconfont icon-sousuo"></span>
        <input type="text" v-model="searchtxt" class="flex-1 ml10 f30 gray3"  placeholder-class="f24 gray6"
               placeholder="搜索商圈" confirm-type="search" @confirm="handleSearch()" />
      </view>
    </view>

    <view class="swiper-view">
      <swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
        <swiper-item v-for="(item, index) in swiperList" :key="index">
          <image :src="item.imgUrl" class="swiper-image" @click="bannerNavToPage(item)"></image>
        </swiper-item>
      </swiper>
    </view>

    <!-- 因为swiper特性的关系，请指定swiper的高度 ，swiper的高度并不会被内容撑开-->
    <view class="grid-wrapper-view">
      <swiper class="grid-swiper" :indicator-dots="false">
        <swiper-item>
          <uni-grid :column="4" :show-border="false" :square="false">
            <uni-grid-item>
              <view class="grid-item-box" @click="navCategory('4')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506190656784.jpg"></image>
                <text class="grid-text">餐饮美食</text>
              </view>
            </uni-grid-item>
            <uni-grid-item>
              <view class="grid-item-box" @click="navCategory('5')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506190909678.jpg"></image>
                <text class="grid-text">亲子乐场</text>
              </view>
            </uni-grid-item>
            <uni-grid-item>
              <view class="grid-item-box" @click="navCategory('6')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506191526121.jpg"></image>
                <text class="grid-text">服饰鞋包</text>
              </view>
            </uni-grid-item>
            <uni-grid-item>
              <view class="grid-item-box" @click="navCategory('7')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506191700460.jpg"></image>
                <text class="grid-text">数码电子</text>
              </view>
            </uni-grid-item>
            <uni-grid-item>
              <view class="grid-item-box" @click="navCategory('8')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506192242868.jpg"></image>
                <text class="grid-text">休闲SAP</text>
              </view>
            </uni-grid-item>
            <uni-grid-item>
              <view class="grid-item-box" @click="navCategory('9')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506192459952.jpg"></image>
                <text class="grid-text">母婴玩具</text>
              </view>
            </uni-grid-item>
            <uni-grid-item>
              <view class="grid-item-box"
                    @click="navCategory('11')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506192721118.png"></image>
                <text class="grid-text">萌宠世界</text>
              </view>
            </uni-grid-item>
            <uni-grid-item>
              <view class="grid-item-box" @click="navCategory('10')">
                <image class="grid-image"
                       src="https://hjapi.tongliansk.com/api/resource/uploads/20240506192838297.jpg"></image>
                <text class="grid-text">景区门票</text>
              </view>
            </uni-grid-item>
          </uni-grid>
        </swiper-item>
      </swiper>
    </view>

    <notice v-if="noticeData && noticeData.type == 'notice'" :itemData="noticeData"></notice>

    <view v-for="(item, index ) in imageSingleData">
      <image style="width: 100%; height: 200rpx; border-radius: 20rpx;margin-bottom: 20rpx;" :src="item.imgUrl" mode="scaleToFill" @click="navToLikePath(item)"></image>
    </view>

    <view style="height: 100rpx; line-height: 100rpx; background: #ffffff;">
      <navBar style="width: 740rpx;" :color='openCategory.color' :isFixedEnable="isFixed" :marginTop="safeHeight"  @currentIndex="setIndex" :navList="categoryList"></navBar>
    </view>

    <view class="business-circles-container" :style="{ minHeight: isFixed ? '100vh' : 'auto' }">
      <view class="business-circle" v-for="(circle, index) in business.list" :key="index">
        <swiper :indicator-dots="true" :autoplay="false" :interval="3000" :duration="500" class="swiper-container"
                @click="navToPage(circle)">
          <swiper-item v-for="(image, index) in circle.image" :key="index">
            <image :src="image.filePath" class="business-swiper-image" mode="aspectFill"></image>
          </swiper-item>
        </swiper>
        <view class="circle-name" @click="navToPage(circle)">{{ circle.businessName }}</view>
        <view class="tip">{{ circle.businessKeyword }}</view>
        <view class="circle-info">
          <view class="info-left">
            <image class="location-icon" src="/static/icon/address_icon.png" mode="aspectFit"></image>
            <text class="location-text">{{ circle.district }}</text>
          </view>
          <view class="info-right">
            <image v-if="circle.isLikeCount" class="like-icon" src="/static/icon/sc-f.png" mode="aspectFit"
                   @click="handleLike(circle,0)"></image>
            <image v-else class="like-icon" src="/static/icon/sc.png" mode="aspectFit"
                   @click="handleLike(circle,1)"></image>
            <text class="like-count">{{ circle.likeCount }}</text>
          </view>
        </view>
      </view>


      <!--点击收藏-->
      <view class="collection-box" v-if="is_collection"  :style="'top:'+(safeHeight*3 + 40)+'rpx;'">
        <view class="inner">
          <text>
            点击“</text>
          <text class="point">.</text>
          <text class="point point-big">.</text>
          <text class="point">.</text>
          <text>”添加到我的小程序，\n微信首页下拉即可快速访问店铺
          </text>
        </view>
        <button type="primary" class="close-btn" @click="is_collection=false">x</button>
      </view>

      <!--关注公众号-->
      <!-- #ifdef MP-WEIXIN -->
      <view class="follow-gzh"  :class="is_auto?'is_auto':''" v-if="is_follow=='1'" >
        <text class="icon iconfont icon-guanbi" @click="is_follow=0"></text>
        <official-account></official-account>
      </view>
      <!-- #endif -->

      <!--首页推送-->
      <Homepush v-if="is_homepush" :homepush_data="homepush_data"></Homepush>

    </view>
    <tabBar></tabBar>
  </view>
</template>

<script>
import notice from '@/components/diy/notice/notice';
import businessUtils from "@/common/businessUtils";
import Homepush from "./home-push/home-push.vue";

export default {
  components: {
    Homepush,
    notice,
  },
  data() {
    return {
      safeHeight: 0,
      pageData:{},
      currentCity: '南宁市',
      swiperList: [],

      noticeData: {},
      current: 0,
      searchtxt:null,
      thisindex: 0,
      openCategory: {
        color: "#000000",
        open: 0
      },
      imageSingleData: [],

      /*收藏引导*/
      is_collection: false,
      is_auto:0,
      /*关注*/
      is_follow: '0',
      /*是否首页推送*/
      is_homepush: false,
      homepush_data:[],

      // 吸顶效果
      isFixed: false,
      offsetTop: 0,
      categoryList: [{
        name: '推荐',
        isRecommend: 1
      }, {
        name: '青秀区',
        category_id: '2165'
      }, {
        name: '江南区',
        category_id: '2166'
      }, {
        name: '西乡塘区',
        category_id: '2167'
      }, {
        name: '良庆区',
        category_id: '2168'
      }, {
        name: '邕宁区',
        category_id: '2169'
      }, {
        name: '兴宁区',
        category_id: '2164'
      }],
      currentDistrictId: null,
      isRecommend: 1, // 默认查推荐的

      notices: [
        {id: 1, content: '这是第一条公告'},
        {id: 2, content: '这是第二条公告'},
        {id: 3, content: '这是第3条公告'},
      ],
      curNoticeIndex: 0,
      noticeIntervalId: null,
      scrollingManually: false,

      cates: [
        {
          cateName: "青秀区",
        }, {
          cateName: "西乡塘区",
        }
      ],
      business: {
        pageIndex: 1,
        pageSize: 10,
        lastPage: 1,
        list: [],
        noMore: false,
      },
      collectionCountList: {},
      likeCountList: {}
    };
  },

  mounted() {
    let self = this;
    uni.getSystemInfo({
      success: function (res) {
        // console.log("getSystemInfo",res);
        self.safeHeight = res.safeAreaInsets.top; // 安全区域顶部高度
        // let safeBottom = res.safeAreaInsets.bottom; // 安全区域底部高度
      }
    });
    this.likeCountList = businessUtils.getLikeCountList();
    this.startAutoScrolling();
    this.getBusinessList();
    // this.getRegionPart();

    this.indexDataInit();
  },
  beforeUnmount() {
    clearInterval(this.noticeIntervalId);
  },
  onReachBottom() {
    let self = this;
    if (self.business.noMore) {
      return;
    }
    self.business.noMore = true;
    if (self.business.pageIndex < self.business.lastPage) {
      self.business.pageIndex++;
      self.getBusinessList();
    } else {
      self.business.noMore = true;
    }

  },


  // 推荐分类菜单吸顶
  onPageScroll(e) {
    // 获取滚动的位置
    const scrollTop = e.scrollTop;
    // console.log("scrollTop",scrollTop,uni.getSystemInfoSync().windowHeight -400);
    // 判断滚动位置是否超过手机屏幕的高度
    if (scrollTop >= (uni.getSystemInfoSync().windowHeight - 400)) {
      // 将菜单添加固定定位样式，使其吸附在顶部
      // 使用uni.$b调用组件，注意选择器的命名可能会有不同
      this.isFixed = true;
    } else {
      // 移除固定定位样式
      this.isFixed = false;
    }
  },


  onShareAppMessage:function(){
    let sid = '';
    /* if(this.userInfo.userUuid){
       sid = this.userInfo.userUuid;
     }*/
    console.log("分享用户ID: "+sid);
    return {
      title: '同城好街，逛街不走冤枉路，与你分享!',
      path: '/pages/index/index?sid='+sid,
      success(res) {
        uni.showToast({
          title: '分享成功',
        })
      },
      fail(res) {
        uni.showToast({
          title: '分享失败',
          icon: 'none',
        })
      },
    }
  },

  onShareTimeline:function(){
    let sid = '';
    return {
      title: '同城好街，逛街不走冤枉路，与你分享!',
      path: '/pages/index/index?sid=' + sid,
      success(res) {
        uni.showToast({
          title: '分享成功',
        })
      },
      fail(res) {
        uni.showToast({
          title: '分享失败',
          icon: 'none',
        })
      },
    }
  },


  methods: {
    //获取后台配置的模板数据
    indexDataInit(){
      let self = this;
      self._get('index/index', {
        url: self.url,
        source: self.getPlatform()
      }, function (res) {
        self.pageData =  res.data;
        if (self.pageData.page.items && self.pageData.page.items.length>0){
          self.pageData.page.items.forEach(function (item,index){
            if (item.type == 'banner'){
              self.swiperList =item.data;
            }else if (item.type == 'notice'){
              self.noticeData = item;
            }else if (item.type == 'imageSingle'){
              self.imageSingleData = item.data;
            }
          });

          //弹出收藏
          // #ifdef  MP-WEIXIN
          let isFirst = uni.getStorageSync('isFirst');
          if (isFirst == '' && res.data.setting.collection.status == '1') {
            self.is_collection = true;
            uni.setStorageSync('isFirst', 1);
          }
          self.is_follow = res.data.setting.officia.status;
          // #endif
          // 首页推送
          let homepush_name = uni.getStorageSync('homepush_name');
          if (res.data.setting.homepush.isOpen && homepush_name != res.data.setting.homepush.name) {
            self.homepush_data = res.data.setting.homepush;
            self.is_homepush = true;
          }

        }
        console.log('index/index', self.pageData)
      })
    },
    bannerNavToPage(row){
      if (row.name){
        uni.navigateTo({
          url: row.name,
        });
      }
    },
    navToPage(row) {
      uni.navigateTo({
        url: '/pages/shop/business_shopList?shopBusinessId=' + row.businessId,
      });
    },

    navCategory(id) {
      uni.navigateTo({
        url: '/pages/shop/supplier_shopList?categoryId='+id
      });
    },

    navToLikePath(item) {
      let path = item.linkUrl?item.linkUrl:item.name;
      uni.navigateTo({
        url: path,
      });
    },

    handleSearch(e) {
      uni.switchTab({
        url: '/pages/shop/business_list'
      });
    },

    startAutoScrolling() {
      this.noticeIntervalId = setInterval(() => {
        if (!this.scrollingManually) {
          this.nextNotice();
        }
      }, 5000);
    },
    handleWheel(event) {
      // 阻止自动滚动
      this.scrollingManually = true;
      // 根据滚轮方向更新currentIndex
      const delta = event.deltaY;
      if (delta < 0) {
        this.prevNotice();
      } else {
        this.nextNotice();
      }
      // 可以在这里设置一个延迟来恢复自动滚动
      // setTimeout(() => { this.scrollingManually = false; }, 2000); // 示例：2秒后恢复
    },

    prevNotice() {
      this.curNoticeIndex = (this.curNoticeIndex - 1 + this.notices.length) % this.notices.length;
    },
    nextNotice() {
      this.curNoticeIndex = (this.curNoticeIndex + 1) % this.notices.length;
    },
    pauseScrolling() {
      // 暂停自动滚动，直到用户再次滚动或点击按钮
      this.scrollingManually = true;
      // 可以在这里设置一个延迟来恢复自动滚动
      // setTimeout(() => { this.scrollingManually = false; this.startAutoScrolling(); }, 2000); // 示例：2秒后恢复
    },

    handleLike(row, value) {
      let self = this;
      self._postBody('business/business/setLikeCount', {
        businessId: row.businessId,
        likeCount: value
      }, (res) => {
        if (value == 1) {
          row.likeCount++;
          row.isLikeCount = true;
          businessUtils.setLikeCount(row.businessId, 1);
          self.likeCountList[businessUtils.likeCountKeyName + row.businessId] = 1;
        } else {
          row.likeCount--;
          row.isLikeCount = false;
          businessUtils.setLikeCount(row.businessId, 0);
          self.likeCountList[businessUtils.likeCountKeyName + row.businessId] = 0;
        }
      })
    },

    //点击nav控制下面的展示
    setIndex(e) {
      this.thisindex = e;
      if (this.categoryList[e].category_id) {
        this.currentDistrictId = this.categoryList[e].category_id;
      } else {
        this.currentDistrictId = null;
      }
      if (this.categoryList[e].isRecommend) {
        this.isRecommend = this.categoryList[e].isRecommend;
      } else {
        this.isRecommend = null;
      }

      this.business.list = [];
      this.business.pageIndex = 1;
      this.business.noMore = false;
      this.getBusinessList();
    },
    getBusinessList() {
      let self = this;
      let pageIndex = self.business.pageIndex;
      let pageSize = self.business.pageSize;
      self.loading = true;
      self._postBody('business/business/list', {
        pageIndex: pageIndex || 1,
        pageSize: pageSize,
        districtId: self.currentDistrictId,
        isRecommend: self.isRecommend,
      }, (res) => {
        self.loading = false;
        self.business.lastPage = res.data.lastPage;
        res.data.records.forEach(item => {
          if (self.likeCountList[businessUtils.likeCountKeyName + item.businessId] && self.likeCountList[businessUtils.likeCountKeyName + item.businessId] == 1) {
            item.isLikeCount = true;
          } else {
            item.isLikeCount = false;
          }
        })
        self.business.list = self.business.list.concat(res.data.records);
        if (res.data.lastPage <= pageIndex) {
          self.business.noMore = true;
        } else {
          self.business.noMore = false;
        }
      })
    },
    //获取市区域
    getRegionPart() {
      let self = this;
      self._postBody('data/region/regionList', {
        pid: 2163
      }, (res) => {
        console.log("getRegionPart", res)
      })
    },

  },
};
</script>

<style scoped>
.container {
  background: #fff;
}

.mp-search-box {
  display: inline-flex;
  width: 100%;
}

.seacth {
  width: 700rpx;
  height: 64rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.mp-search-box .city {
  margin: 0 10upx 0 0;
  height: 40upx;
  line-height: 40upx;
}

.mp-search-box .city .city-name {
  font-size: 28upx;
}

.down-icon {
  width: 22upx;
  height: 22upx;
  margin: 10upx;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 10upx;
  background-color: #fff;
  width: 100%;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  border: 1px solid #ccc; /* 边框 */
  border-radius: 50upx; /* 圆角 */
  overflow: hidden; /* 隐藏超出部分 */
  width: 90%;
  height: 66upx;
}

.search-input {
  flex: 1; /* 占据剩余空间 */
  padding: 5px; /* 内边距 */
  border: none; /* 去除默认边框 */
  outline: none; /* 去除点击时的边框 */
  font-size: 16px; /* 字体大小 */
}

.search-btn {
  padding: 0 10px; /* 内边距 */
  background-color: #409EFF; /* 背景色 */
  color: #fff; /* 文字颜色 */
  border: none; /* 去除默认边框 */
  border-radius: 0 4px 4px 0; /* 右边圆角 */
}

.saoma {
  width: 80upx;
  height: 80upx;
  margin-left: 30upx;
  margin-right: 30upx;
}

.swiper-view {
  background-color: #fff;
}

.swiper-image {
  width: 100%;
  height: 200px;
}

.grid-wrapper-view {
  background-color: #ffffff;
  position: relative;
  z-index: 5;
  border-radius: 16upx 16upx 0 0;
}

.grid-swiper {
  display: flex;
  width: 100%;
  height: 344upx;
}

.grid-item-box {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
  width: 25%;
}

.grid-image {
  width: 80upx;
  height: 80upx;
  border-radius: 50%;
}

.grid-text {
  color: #303133;

}

.notice-container {
  position: relative;
  height: 200px; /* 设置你的公告栏高度 */
  overflow: hidden;
}

.notice-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  /* 其他样式 */
}

/* 滑动过渡效果 */
.slide-enter-active, .slide-leave-active {
  transition: transform 0.5s;
}

.slide-enter, .slide-leave-to {
  transform: translateY(100%);
}


.grid-dot {
  position: absolute;
  top: 5px;
  right: 15px;
}

.diy-notice {
  margin: 20rpx;
  padding: 8upx;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-radius: 6rpx;
  background: rgb(253, 246, 236);
  /* box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.1); */

}

.diy-notice .notice-icon {
  width: 54rpx;
  height: 54rpx;
  margin-right: 20rpx;
}

.diy-notice .notice-icon image {
  width: 100%;
  height: 100%;
}

.diy-notice .notice-text {
  overflow: hidden;
  white-space: nowrap;

}

.transtext {
  min-width: 586rpx;
  flex-shrink: 0;
  white-space: nowrap;
  float: left;
}

.business-circles-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.business-circle {
  flex: 0 0 calc(50% - 10upx);
  box-sizing: border-box;
  margin: 20upx 0 20upx 0;
}

.swiper-container {
  width: 100%;
  height: 200px;
}

.business-swiper-image {
  width: 100%;
  height: 100%;
  border-radius: 16upx;
}

.circle-name {
  font-size: 28upx;
  font-weight: bold;
  margin-top: 20upx;
}

.circle-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.info-left, .info-right {
  display: flex;
  align-items: center;
}

.city {
  display: inline-flex;
  justify-content: center;
  justify-items: center;
}

.location-icon, .like-icon {
  width: 34upx;
  height: 36upx;
  margin-right: 6upx;
  display: inline-flex;
}

.location-text, .like-count {
  font-size: 14px;
  display: inline-flex;
}

.tip {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  -webkit-line-clamp: 2;
}



.collection-box {
  position: fixed;
  width: 380rpx;
  padding: 20rpx;
  top: 20rpx;
  right: 20rpx;
  line-height: 40rpx;
  font-size: 24rpx;
  border-radius: 16rpx;
  background: #ffffff;
  border: 1px solid #eeeeee;
  box-shadow: 0 0 6rpx 0 rgba(0, 0, 0, .08);
  z-index: 100;
}

.collection-box::after {
  position: absolute;
  content: '';
  display: block;
  right: 140rpx;
  top: -15rpx;
  transform: rotate(45deg);
  width: 30rpx;
  height: 30rpx;
  transform: rotate;
  background: #FFFFFF;
  border-left: 1px solid #eeeeee;
  border-top: 1px solid #eeeeee;
}

.collection-box .point {
  width: 20rpx;
  height: 20rpx;
  font-size: 60rpx;
  line-height: 0;
  color: #666666;
}

.collection-box .point-big {
  font-size: 80rpx;
}

.collection-box .close-btn {
  position: absolute;
  padding: 0;
  right: 10rpx;
  top: 10rpx;
  width: 40rpx;
  height: 40rpx;
  line-height: 30rpx;
  background: #FFFFFF;
  color: #999999;
  border-radius: 50%;
}

.follow-gzh {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  border-radius: 16rpx;
  box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, .1);
  background: #ffffff;
  z-index: 10;
}
.follow-gzh.is_auto{
  bottom: calc(env(safe-area-inset-bottom) + 98rpx);
}
.follow-gzh .iconfont {
  display: block;
  position: absolute;
  right: 10rpx;
  top: 10rpx;
  z-index: 99;
}

</style>
